{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wArePITKUgQG"
      },
      "source": [
        "<img src=\"aiayn.png\">"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tSWEk4ttUgQH"
      },
      "source": [
        "> When teaching, I emphasize implementation as a way to understand recent developments in ML. This post is an attempt to keep myself honest along this goal. The recent [\"Attention is All You Need\"]\n",
        "(https://arxiv.org/abs/1706.03762) paper from NIPS 2017 has been instantly impactful paper as a new method for machine translation and potentiall NLP generally. The paper is very clearly written, but the conventional wisdom has been that it is quite difficult to implement correctly.\n",
        ">\n",
        "> In this post I follow the paper through from start to finish and try to implement each component in code.\n",
        "(I have done some minor reordering and skipping from the original paper). This document itself is a working notebook, and should be a completely usable and efficient implementation. To follow along you will first need to install [PyTorch](http://pytorch.org/) and [torchtext](https://github.com/pytorch/text). The complete code is available on [github](https://github.com/harvardnlp/annotated-transformer).\n",
        ">- Alexander \"Sasha\" Rush ([@harvardnlp](https://twitter.com/harvardnlp))\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lLtGx9F-vXCG",
        "outputId": "377847d9-d7df-421e-a762-fab7917517ce"
      },
      "outputs": [],
      "source": [
        "!pip install transformers datasets"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_R749nLNUgQL"
      },
      "source": [
        "* Table of Contents                               \n",
        "{:toc}      "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4LTc4HW7UgQI"
      },
      "outputs": [],
      "source": [
        "# Standard PyTorch imports\n",
        "import numpy as np\n",
        "import torch\n",
        "import torch.nn as nn\n",
        "import torch.nn.functional as F\n",
        "import math, copy\n",
        "from torch.autograd import Variable\n",
        "\n",
        "# For plots\n",
        "%matplotlib inline\n",
        "import matplotlib.pyplot as plt\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "esxhOQubUgQL"
      },
      "source": [
        "# Background"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1M-PiEMOUgQM"
      },
      "source": [
        "The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU\n",
        "[16], ByteNet [18] and ConvS2S [9], all of which use convolutional neural networks as basic building\n",
        "block, computing hidden representations in parallel for all input and output positions. In these models,\n",
        "the number of operations required to relate signals from two arbitrary input or output positions grows\n",
        "in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes\n",
        "it more difficult to learn dependencies between distant positions [12]. In the Transformer this is\n",
        "reduced to a constant number of operations, albeit at the cost of reduced effective resolution due\n",
        "to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as\n",
        "described in section 3.2.\n",
        "\n",
        "Self-attention, sometimes called intra-attention is an attention mechanism relating different positions\n",
        "of a single sequence in order to compute a representation of the sequence. Self-attention has been\n",
        "used successfully in a variety of tasks including reading comprehension, abstractive summarization,\n",
        "textual entailment and learning task-independent sentence representations [4, 27, 28, 22].\n",
        "End-to-end memory networks are based on a recurrent attention mechanism instead of sequencealigned\n",
        "recurrence and have been shown to perform well on simple-language question answering and\n",
        "language modeling tasks [34].\n",
        "\n",
        "To the best of our knowledge, however, the Transformer is the first transduction model relying\n",
        "entirely on self-attention to compute representations of its input and output without using sequencealigned\n",
        "RNNs or convolution. In the following sections, we will describe the Transformer, motivate\n",
        "self-attention and discuss its advantages over models such as [17, 18] and [9]."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "84vTAA5TUgQM"
      },
      "source": [
        "# Model Architecture"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "f-f9BuNsUgQN"
      },
      "source": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VBOvyU9BUgQN"
      },
      "source": [
        "Most competitive neural sequence transduction models have an encoder-decoder structure [(cite)](cho2014learning,bahdanau2014neural,sutskever14). Here, the encoder maps an input sequence of symbol representations $(x_1, ..., x_n)$ to a sequence of continuous representations $\\mathbf{z} = (z_1, ..., z_n)$. Given $\\mathbf{z}$, the decoder then generates an output sequence $(y_1,...,y_m)$ of symbols one element at a time. At each step the model is auto-regressive [(cite)](graves2013generating), consuming the previously generated symbols as additional input when generating the next."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1AC8KeDJUgQO"
      },
      "outputs": [],
      "source": [
        "class EncoderDecoder(nn.Module):\n",
        "    \"\"\"\n",
        "    A standard Encoder-Decoder architecture. Base model for this and many\n",
        "    other models.\n",
        "    \"\"\"\n",
        "    def __init__(self, encoder, decoder, src_embed, tgt_embed, generator):\n",
        "        super(EncoderDecoder, self).__init__()\n",
        "        self.encoder = encoder\n",
        "        self.decoder = decoder\n",
        "        self.src_embed = src_embed\n",
        "        self.tgt_embed = tgt_embed\n",
        "        self.generator = generator\n",
        "\n",
        "    def forward(self, src, tgt, src_mask, tgt_mask):\n",
        "        \"Take in and process masked src and target sequences.\"\n",
        "        memory = self.encoder(self.src_embed(src), src_mask)\n",
        "        output = self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask)\n",
        "        return output"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ip0EXqvEUgQQ"
      },
      "source": [
        "The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "q9dznVhQUgQQ"
      },
      "source": [
        "<img src=\"ModalNet-21.png\" width=400px>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "euyRXbaMUgQR"
      },
      "source": [
        "## Encoder and Decoder Stacks   \n",
        "\n",
        "### Encoder:\n",
        "\n",
        "The encoder is composed of a stack of $N=6$ identical layers."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6yy7pY85UgQR"
      },
      "outputs": [],
      "source": [
        "def clones(module, N):\n",
        "    \"Produce N identical layers.\"\n",
        "    return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "psiq5idJUgQT"
      },
      "outputs": [],
      "source": [
        "class Encoder(nn.Module):\n",
        "    \"Core encoder is a stack of N layers\"\n",
        "    def __init__(self, layer, N):\n",
        "        super(Encoder, self).__init__()\n",
        "        self.layers = clones(layer, N)\n",
        "        self.norm = LayerNorm(layer.size)\n",
        "\n",
        "    def forward(self, x, mask):\n",
        "        \"Pass the input (and mask) through each layer in turn.\"\n",
        "        for layer in self.layers:\n",
        "            x = layer(x, mask)\n",
        "        return self.norm(x)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Mie9sUeSUgQV"
      },
      "source": [
        "We employ a residual connection [(cite)](he2016deep) around each of the two sub-layers, followed by layer normalization [(cite)](layernorm2016).  "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sEz9kLClUgQV"
      },
      "outputs": [],
      "source": [
        "class LayerNorm(nn.Module):\n",
        "    \"Construct a layernorm module (See citation for details).\"\n",
        "    def __init__(self, features, eps=1e-6):\n",
        "        super(LayerNorm, self).__init__()\n",
        "        self.a_2 = nn.Parameter(torch.ones(features))\n",
        "        self.b_2 = nn.Parameter(torch.zeros(features))\n",
        "        self.eps = eps\n",
        "\n",
        "    def forward(self, x):\n",
        "        mean = x.mean(-1, keepdim=True)\n",
        "        std = x.std(-1, keepdim=True)\n",
        "        return self.a_2 * (x - mean) / (std + self.eps) + self.b_2"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nx4On5PCUgQY"
      },
      "source": [
        "That is, the output of each sub-layer is $\\mathrm{LayerNorm}(x + \\mathrm{Sublayer}(x))$, where $\\mathrm{Sublayer}(x)$ is the function implemented by the sub-layer itself.  We apply dropout [(cite)](srivastava2014dropout) to the output of each sub-layer, before it is added to the sub-layer input and normalized.  \n",
        "\n",
        "To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension $d_{\\text{model}}=512$.  "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zx9JBwAcUgQY"
      },
      "outputs": [],
      "source": [
        "class SublayerConnection(nn.Module):\n",
        "    \"\"\"\n",
        "    A residual connection followed by a layer norm.\n",
        "    Note for code simplicity we apply the norm first as opposed to last.\n",
        "    \"\"\"\n",
        "    def __init__(self, size, dropout):\n",
        "        super(SublayerConnection, self).__init__()\n",
        "        self.norm = LayerNorm(size)\n",
        "        self.dropout = nn.Dropout(dropout)\n",
        "\n",
        "    def forward(self, x, sublayer):\n",
        "        \"Apply residual connection to any sublayer function that maintains the same size.\"\n",
        "        return x + self.dropout(sublayer(self.norm(x)))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZduB6mIlUgQa"
      },
      "source": [
        "Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position-wise fully connected feed-forward network.\n",
        "在编码层的内部有两个部分：第一个部分为多头自注意力层，第二个部分为一般的前馈神经网络层（以全连接层进行实现）"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0mEBw9tIUgQb"
      },
      "outputs": [],
      "source": [
        "class EncoderLayer(nn.Module):\n",
        "    \"Encoder is made up of two sublayers, self-attn and feed forward (defined below)\"\n",
        "    def __init__(self, size, self_attn, feed_forward, dropout):\n",
        "        super(EncoderLayer, self).__init__()\n",
        "        self.self_attn = self_attn\n",
        "        self.feed_forward = feed_forward\n",
        "        self.sublayer = clones(SublayerConnection(size, dropout), 2)\n",
        "        self.size = size\n",
        "\n",
        "    def forward(self, x, mask):\n",
        "        \"Follow Figure 1 (left) for connections.\"\n",
        "        x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))\n",
        "        return self.sublayer[1](x, self.feed_forward)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iHOZnpnBUgQd"
      },
      "source": [
        "### Decoder:\n",
        "\n",
        "The decoder is also composed of a stack of $N=6$ identical layers.  \n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3o_ZB42sUgQd"
      },
      "outputs": [],
      "source": [
        "class Decoder(nn.Module):\n",
        "    \"Generic N layer decoder with masking.\"\n",
        "    def __init__(self, layer, N):\n",
        "        super(Decoder, self).__init__()\n",
        "        self.layers = clones(layer, N)\n",
        "        self.norm = LayerNorm(layer.size)\n",
        "\n",
        "    def forward(self, x, memory, src_mask, tgt_mask):\n",
        "        for layer in self.layers:\n",
        "            x = layer(x, memory, src_mask, tgt_mask)\n",
        "        return self.norm(x)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dOi_W1qaUgQf"
      },
      "source": [
        "In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack.  Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization.  \n",
        "以下代码的说明(待更新和补充)\n",
        "- m表示从编码器的结果的输出，将会作为K，V的输入\n",
        "- 每一层有两个attention block\n",
        "    - 第一个为解码层内部的attention，一般会采用因果的自注意力机制，通过mask相结合进行实现\n",
        "    - 第二个为和编码层的attention的输出进行交叉自注意力机制的实现，这里的mask为src的mask，因为src有部分采用了padding，只需计算有信息部分的自注意力的相关矩阵的部分\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "kMm6xHWVUgQg"
      },
      "outputs": [],
      "source": [
        "class DecoderLayer(nn.Module):\n",
        "    \"Decoder is made up of three sublayers, self-attn, src-attn, and feed forward (defined below)\"\n",
        "    def __init__(self, size, self_attn, src_attn, feed_forward, dropout):\n",
        "        super(DecoderLayer, self).__init__()\n",
        "        self.size = size\n",
        "        self.self_attn = self_attn\n",
        "        self.src_attn = src_attn\n",
        "        self.feed_forward = feed_forward\n",
        "        self.sublayer = clones(SublayerConnection(size, dropout), 3)\n",
        "\n",
        "    def forward(self, x, memory, src_mask, tgt_mask):\n",
        "        \"Follow Figure 1 (right) for connections.\"\n",
        "        m = memory\n",
        "        x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))\n",
        "        x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask))\n",
        "        return self.sublayer[2](x, self.feed_forward)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3Nen9h7wUgQi"
      },
      "source": [
        "We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions.  This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position $i$ can depend only on the known outputs at positions less than $i$.\n",
        "\n",
        "亦即因果(causual self attention block)自注意力机制的实现\n",
        "创建一个注意力掩码（Attention Mask）。这个特殊的掩码通常被称为**“后续掩码” (Subsequent Mask)** 或 “前瞻掩码” (Look-ahead Mask)\n",
        "在自然语言生成任务中，比如机器翻译，模型在生成第 i 个词时，只能依赖于它已经生成的前 i-1 个词，而不能“偷看”未来的词（即第 i 个、第 i+1 个词等）。\n",
        "在计算自注意力（Self-Attention）时，它会**遮挡（mask out）**掉所有未来的位置，确保每个位置的输出只依赖于当前和之前的位置。\n",
        "np.ones(attn_shape): 创建一个形状为 (1, size, size)、所有元素都为 1 的 NumPy 数组。\n",
        "np.triu (triangle upper) 的作用是保留一个矩阵的上三角部分，将其余部分置为 0。参数 k 控制着对角线的位置：\n",
        "- k=0 (默认): 保留主对角线及以上部分。\n",
        "- k=1: 保留主对角线上方的部分，主对角线本身也被置为 0。\n",
        "- k=-1: 保留主对角线下方部分。\n",
        "\n",
        "torch.from_numpy(subsequent_mask) == 0有类似取反的作用\n",
        "- 原来是 0 的位置，比较后变为 True。\n",
        "- 原来是 1 的位置，比较后变为 False。\n",
        "\n",
        "scores 是注意力分数张量，形状通常是 (batch_size, num_heads, seq_len, seq_len)  \n",
        "scores = scores.masked_fill(mask == False, -1e9)  \n",
        "将掩码中为 False 的位置（即我们想遮挡的未来位置）对应的注意力分数替换成一个非常大的负数（如 -1e9）。当这个带有极大负数的张量经过 Softmax 函数时，这些位置的概率会趋近于 0，从而有效地“忽略”了它们。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RyQKI9AgUgQj"
      },
      "outputs": [],
      "source": [
        "def subsequent_mask(size):\n",
        "    \"Mask out subsequent positions.\"\n",
        "    attn_shape = (1, size, size)\n",
        "    subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')\n",
        "    return torch.from_numpy(subsequent_mask) == 0"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 462
        },
        "id": "fgQMtvM-UgQl",
        "outputId": "f4b9d18a-ca93-4ad5-a9a8-fe9d31db99df"
      },
      "outputs": [],
      "source": [
        "# The attention mask shows the position each tgt word (row) is allowed to look at (column).\n",
        "# Words are blocked for attending to future words during training.\n",
        "import os\n",
        "os.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"TRUE\"\n",
        "\n",
        "plt.figure(figsize=(5,5))\n",
        "plt.imshow(subsequent_mask(20)[0])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fl2E1IaqUgQq"
      },
      "source": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3twSbimFUgQq"
      },
      "source": [
        "### Attention:                                                                                                                                                                                                                                                                               \n",
        "An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors.  The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.                                                                                                                                                                                                                                                                                           \n",
        "\n",
        "We call our particular attention \"Scaled Dot-Product Attention\".   The input consists of queries and keys of dimension $d_k$, and values of dimension $d_v$.  We compute the dot products of the query with all keys, divide each by $\\sqrt{d_k}$, and apply a softmax function to obtain the weights on the values.                                                                                                         \n",
        "<img width=\"220px\" src=\"ModalNet-19.png\">\n",
        "\n",
        "In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix $Q$.   The keys and values are also packed together into matrices $K$ and $V$.  We compute the matrix of outputs as:                      \n",
        "                                                                 \n",
        "$$                                                                         \n",
        "   \\mathrm{Attention}(Q, K, V) = \\mathrm{softmax}(\\frac{QK^T}{\\sqrt{d_k}})V               \n",
        "$$       \n",
        "\n",
        "自注意力机制的代码实现，这里用到了mask，mask为0的地方将不参与计算（经过softmax计算后其概率比重为0）\n",
        "\n",
        "torch.matmul 的内部实现比这更高效，它使用的是一种叫做**批处理矩阵乘法（Batch Matrix Multiplication）**的机制\n",
        "\n",
        "当 torch.matmul(tensor1, tensor2) 的输入张量维度大于 2 时，它遵循以下规则：\n",
        "最后两维是矩阵：torch.matmul 将每个张量的最后两个维度视为要进行乘法运算的矩阵。\n",
        "前面所有维度是“批次”维度：除最后两维之外的所有维度都被视为“批次”维度。torch.matmul 会在这些批次维度上进行广播（broadcasting）。\n",
        "独立计算：它会把运算看作是一批独立的矩阵乘法。对于批次维度中的每一个组合，它都会执行一次标准的 2D 矩阵乘法。\n",
        "关键在于：这个“批处理”操作不是通过 Python 循环实现的，而是在底层（如 C++ 或 CUDA）通过高度优化的代码执行的，能够充分利用硬件的并行计算能力。\n",
        "\n",
        "以[batch, multi-head-count, tokens_capacity, d_k] 形状为例来分析。为了方便，我们用符号表示：[B, H, T, Dk]。  \n",
        "B: batch_size (批次大小)  \n",
        "H: multi-head-count (头的数量)  \n",
        "T: tokens_capacity (序列长度)  \n",
        "Dk: d_k (每个头的维度)  \n",
        "计算 scores  scores = torch.matmul(query, key.transpose(-2, -1))    \n",
        "query 的形状: (B, H, T, Dk)  \n",
        "key 的形状: (B, H, T, Dk)  \n",
        "key.transpose(-2, -1) 的形状:  \n",
        "transpose(-2, -1) 会交换最后两个维度。  \n",
        "所以，形状变为 (B, H, Dk, T)。  \n",
        "现在，我们来看 torch.matmul 的输入：  \n",
        "tensor1 (query): (B, H, T, Dk)  \n",
        "tensor2 (key.transpose(...)): (B, H, Dk, T)    \n",
        "因此，scores 的最终形状是 (B, H, T, T)，这正是我们期望的注意力分数矩阵的形状（对于每个头和每个批次项）"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wlZ8zw9PUgQr"
      },
      "outputs": [],
      "source": [
        "def attention(query, key, value, mask=None, dropout=0.0):\n",
        "    \"Compute 'Scaled Dot Product Attention'\"\n",
        "    d_k = query.size(-1)\n",
        "    scores = torch.matmul(query, key.transpose(-2, -1)) \\\n",
        "             / math.sqrt(d_k)\n",
        "    if mask is not None:\n",
        "        scores = scores.masked_fill(mask == 0, -1e9)\n",
        "    p_attn = F.softmax(scores, dim = -1)\n",
        "    # (Dropout described below)\n",
        "    p_attn = F.dropout(p_attn, p=dropout)\n",
        "    return torch.matmul(p_attn, value), p_attn"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AV7cIqbrUgQs"
      },
      "source": [
        "The two most commonly used attention functions are additive attention [(cite)](bahdanau2014neural), and dot-product (multiplicative) attention.  Dot-product attention is identical to our algorithm, except for the scaling factor of $\\frac{1}{\\sqrt{d_k}}$. Additive attention computes the compatibility function using a feed-forward network with a single hidden layer.  While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.                                                                                             \n",
        "\n",
        "                                                                        \n",
        "While for small values of $d_k$ the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of $d_k$ [(cite)](DBLP:journals/corr/BritzGLL17). We suspect that for large values of $d_k$, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients  (To illustrate why the dot products get large, assume that the components of $q$ and $k$ are independent random variables with mean $0$ and variance $1$.  Then their dot product, $q \\cdot k = \\sum_{i=1}^{d_k} q_ik_i$, has mean $0$ and variance $d_k$.). To counteract this effect, we scale the dot products by $\\frac{1}{\\sqrt{d_k}}$.          "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OV7kNMbKUgQt"
      },
      "source": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uiaCxaGGUgQt"
      },
      "source": [
        "### Multi-Head Attention                                                                                                                                                                                                                                                                                                                                                                                                                               \n",
        "                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          \n",
        "Instead of performing a single attention function with $d_{\\text{model}}$-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values $h$ times with different, learned linear projections to $d_k$, $d_k$ and $d_v$ dimensions, respectively.                                                                                                                                                                                                   \n",
        "On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding $d_v$-dimensional output values. These are concatenated and once again projected, resulting in the final values:\n",
        "\n",
        "<img width=\"270px\" src=\"ModalNet-20.png\">\n",
        "                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          \n",
        "Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.                                                                                                                                                                                                                                                                                             \n",
        "    \n",
        "    \n",
        "   \n",
        "$$    \n",
        "\\mathrm{MultiHead}(Q, K, V) = \\mathrm{Concat}(\\mathrm{head_1}, ..., \\mathrm{head_h})W^O    \\\\                                           \n",
        "    \\text{where}~\\mathrm{head_i} = \\mathrm{Attention}(QW^Q_i, KW^K_i, VW^V_i)                                \n",
        "$$                                                                                                                                                                                                                                                                                                                                                                         \n",
        "                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          \n",
        "Where the projections are parameter matrices $W^Q_i \\in \\mathbb{R}^{d_{\\text{model}} \\times d_k}$, $W^K_i \\in \\mathbb{R}^{d_{\\text{model}} \\times d_k}$, $W^V_i \\in \\mathbb{R}^{d_{\\text{model}} \\times d_v}$ and $W^O \\in \\mathbb{R}^{hd_v \\times d_{\\text{model}}}$.                                                                                                                                                                                                                                                        \n",
        "   \n",
        "\n",
        "   \n",
        "In this work we employ $h=8$ parallel attention layers, or heads. For each of these we use $d_k=d_v=d_{\\text{model}}/h=64$. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.   \n",
        "\n",
        "\n",
        "多头自注意力机制的实现，h为head的数目，d_model为模型的输出的维度(batch_size, token_capacity, d_model)\n",
        "```\n",
        "def clones(module, N):\n",
        "    \"Produce N identical layers.\"\n",
        "    return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])\n",
        "\n",
        "query, key, value = [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)\n",
        "                    for l, x in zip(self.linears, (query, key, value))]\n",
        "```\n",
        "\n",
        "zip 函数在打包多个可迭代对象（如列表、元组）时，会以其中最短的那个为准。 一旦最短的可迭代对象耗尽，zip 就会停止。\n",
        "self.linears: 这是一个 nn.ModuleList，通过 clones(..., 4) 创建，其长度为 4。\n",
        "[Linear_Layer_0, Linear_Layer_1, Linear_Layer_2, Linear_Layer_3]\n",
        "(query, key, value): 这是一个元组，包含了三个张量，其长度为 3。\n",
        "因此，zip(self.linears, (query, key, value)) 只会产生三对元素：\n",
        "- (self.linears[0], query)\n",
        "- (self.linears[1], key)\n",
        "- (self.linears[2], value)\n",
        "self.linears 中的第四个线性层 (self.linears[3]) 在这个列表推导中不会被使用。而在后续融合的使用\n",
        "```\n",
        "self.linears[-1](x)\n",
        "```\n",
        "\n",
        "关于attention的高阶张量的计算说明在上面已有提及。\n",
        "下面这句代码将多个head的结果合并到到一起，形成[B,T,d_model]的张量输出   \n",
        "最后再通过线性层进行一次融合后形成最终的张量输出[B,T,d_model]  \n",
        "```\n",
        "x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)\\\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_ea0UrEgUgQt"
      },
      "outputs": [],
      "source": [
        "class MultiHeadedAttention(nn.Module):\n",
        "    def __init__(self, h, d_model, dropout=0.1):\n",
        "        \"Take in model size and number of heads.\"\n",
        "        super(MultiHeadedAttention, self).__init__()\n",
        "        assert d_model % h == 0\n",
        "        # We assume d_v always equals d_k\n",
        "        self.d_k = d_model // h\n",
        "        self.h = h\n",
        "        self.p = dropout\n",
        "        self.linears = clones(nn.Linear(d_model, d_model), 4)\n",
        "        self.attn = None\n",
        "\n",
        "    def forward(self, query, key, value, mask=None):\n",
        "        \"Implements Figure 2\"\n",
        "        if mask is not None:\n",
        "            # Same mask applied to all h heads.\n",
        "            mask = mask.unsqueeze(1)\n",
        "        nbatches = query.size(0)\n",
        "\n",
        "        # 1) Do all the linear projections in batch from d_model => h x d_k\n",
        "        query, key, value = [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)\n",
        "                             for l, x in zip(self.linears, (query, key, value))]\n",
        "\n",
        "        # 2) Apply attention on all the projected vectors in batch.\n",
        "        x, self.attn = attention(query, key, value, mask=mask, dropout=self.p)\n",
        "\n",
        "        # 3) \"Concat\" using a view and apply a final linear.\n",
        "        x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)\n",
        "        return self.linears[-1](x)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aVdpQ_KwUgQv"
      },
      "source": [
        "### Applications of Attention in our Model                                                                                                                                                      \n",
        "The Transformer uses multi-head attention in three different ways:                                                        \n",
        "1) In \"encoder-decoder attention\" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder.   This allows every position in the decoder to attend over all positions in the input sequence.  This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as [(cite)](wu2016google, bahdanau2014neural,JonasFaceNet2017).    \n",
        "\n",
        "\n",
        "2) The encoder contains self-attention layers.  In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder.   Each position in the encoder can attend to all positions in the previous layer of the encoder.                                                   \n",
        "\n",
        "\n",
        "3) Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position.  We need to prevent leftward information flow in the decoder to preserve the auto-regressive property.  We implement this inside of scaled dot-product attention by masking out (setting to $-\\infty$) all values in the input of the softmax which correspond to illegal connections.                                                                                                                                                                                                                                                      "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gERLhK-FUgQw"
      },
      "source": [
        "## Position-wise Feed-Forward Networks                                                                                                                                                                                                                                                                                                                                                             \n",
        "                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          \n",
        "In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically.  This consists of two linear transformations with a ReLU activation in between.\n",
        "\n",
        "$$\\mathrm{FFN}(x)=\\max(0, xW_1 + b_1) W_2 + b_2$$                                                                                                                                                                                                                                                         \n",
        "                                                                                                                                                                                                                                                        \n",
        "While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1.  The dimensionality of input and output is $d_{\\text{model}}=512$, and the inner-layer has dimensionality $d_{ff}=2048$.\n",
        "\n",
        "全连接前馈层，两层全连接网络"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HuDPthO2UgQx"
      },
      "outputs": [],
      "source": [
        "class PositionwiseFeedForward(nn.Module):\n",
        "    \"Implements FFN equation.\"\n",
        "    def __init__(self, d_model, d_ff, dropout=0.1):\n",
        "        super(PositionwiseFeedForward, self).__init__()\n",
        "        # Torch linears have a `b` by default.\n",
        "        self.w_1 = nn.Linear(d_model, d_ff)\n",
        "        self.w_2 = nn.Linear(d_ff, d_model)\n",
        "        self.dropout = nn.Dropout(dropout)\n",
        "\n",
        "    def forward(self, x):\n",
        "        return self.w_2(self.dropout(F.relu(self.w_1(x))))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "68VLwifsUgQz"
      },
      "source": [
        "## Embeddings and Softmax                                                                                                                                                                                                                                                                                           \n",
        "Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension $d_{\\text{model}}$.  We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities.  In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [(cite)](press2016using). In the embedding layers, we multiply those weights by $\\sqrt{d_{\\text{model}}}$.              \n",
        "\n",
        "嵌入层，从输入到transformer的模型维度d_model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sl5JzPeGUgQz"
      },
      "outputs": [],
      "source": [
        "class Embeddings(nn.Module):\n",
        "    def __init__(self, d_model, vocab):\n",
        "        super(Embeddings, self).__init__()\n",
        "        self.lut = nn.Embedding(vocab, d_model)\n",
        "        self.d_model = d_model\n",
        "\n",
        "    def forward(self, x):\n",
        "        return self.lut(x) * math.sqrt(self.d_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F_hw5TyCUgQ1"
      },
      "source": [
        "## Positional Encoding                                                                                                                             \n",
        "Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence.  To this end, we add \"positional encodings\" to the input embeddings at the bottoms of the encoder and decoder stacks.  The positional encodings have the same dimension $d_{\\text{model}}$ as the embeddings, so that the two can be summed.   There are many choices of positional encodings, learned and fixed [(cite)](JonasFaceNet2017).\n",
        "\n",
        "In this work, we use sine and cosine functions of different frequencies:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n",
        "$$                                                                                                                                                                                                                                                                                                                                                                                                                                                                            \n",
        "    PE_{(pos,2i)} = sin(pos / 10000^{2i/d_{\\text{model}}}) \\\\                                                                                                                                                                                                                                                                                                                                                                                                                                      \n",
        "    PE_{(pos,2i+1)} = cos(pos / 10000^{2i/d_{\\text{model}}})                                                                                                                                                                                                                                                                                                                                                                                                                                       \n",
        "$$                                                                                                                                                                                                                                                        \n",
        "where $pos$ is the position and $i$ is the dimension.  That is, each dimension of the positional encoding corresponds to a sinusoid.  The wavelengths form a geometric progression from $2\\pi$ to $10000 \\cdot 2\\pi$.  We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset $k$, $PE_{pos+k}$ can be represented as a linear function of $PE_{pos}$.\n",
        "\n",
        "In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks.  For the base model, we use a rate of $P_{drop}=0.1$.\n",
        "\n",
        "位置编码，         \n",
        "\n",
        "$$\n",
        "e^{2i*(-log(10000)/d)}= e^{-log(10000)*(2i/d)}=\\frac{1}{e^{log(10000)^{(2i/d)}}}=\\frac{1}{(10000)^{(2i/d)}}\n",
        "$$\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MVsjhp6uUgQ1"
      },
      "outputs": [],
      "source": [
        "class PositionalEncoding(nn.Module):\n",
        "    \"Implement the PE function.\"\n",
        "    def __init__(self, d_model, dropout, max_len=5000):\n",
        "        super(PositionalEncoding, self).__init__()\n",
        "        self.dropout = nn.Dropout(p=dropout)\n",
        "\n",
        "        # Compute the positional encodings once in log space.\n",
        "        pe = torch.zeros(max_len, d_model)\n",
        "        position = torch.arange(0, max_len).unsqueeze(1)\n",
        "        div_term = torch.exp(torch.arange(0, d_model, 2) *\n",
        "                             -(math.log(10000.0) / d_model))\n",
        "        pe[:, 0::2] = torch.sin(position * div_term)\n",
        "        pe[:, 1::2] = torch.cos(position * div_term)\n",
        "        pe = pe.unsqueeze(0)\n",
        "        self.register_buffer('pe', pe)\n",
        "\n",
        "    def forward(self, x):\n",
        "        x = x + Variable(self.pe[:, :x.size(1)], requires_grad=False)\n",
        "        return self.dropout(x)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "如下代码说明：d_model=20,T=100"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 445
        },
        "id": "qMsBRCuLUgQ3",
        "outputId": "b020b496-1fb6-4469-dc65-9145b403f110"
      },
      "outputs": [],
      "source": [
        "# The positional encoding will add in a sine wave based on position.\n",
        "# The frequency and offset of the wave is different for each dimension.\n",
        "plt.figure(figsize=(15, 5))\n",
        "pe = PositionalEncoding(20, 0)\n",
        "y = pe.forward(Variable(torch.zeros(1, 100, 20)))\n",
        "plt.plot(np.arange(100), y[0, :, 4:8].data.numpy())\n",
        "plt.legend([\"dim %d\"%p for p in [4,5,6,7]])\n",
        "None"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6HjtmgH1UgQ5"
      },
      "source": [
        "We also experimented with using learned positional embeddings [(cite)](JonasFaceNet2017) instead, and found that the two versions produced nearly identical results.  We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.    "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZtnFnHH9UgQ6"
      },
      "source": [
        "## Generation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "heaKRIaZUgQ6"
      },
      "outputs": [],
      "source": [
        "class Generator(nn.Module):\n",
        "    \"Standard generation step. (Not described in the paper.)\"\n",
        "    def __init__(self, d_model, vocab):\n",
        "        super(Generator, self).__init__()\n",
        "        self.proj = nn.Linear(d_model, vocab)\n",
        "\n",
        "    def forward(self, x):\n",
        "        return F.log_softmax(self.proj(x), dim=-1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dd3lP9fTUgQ9"
      },
      "source": [
        "## Full Model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "b-LDhRoaUgQ-"
      },
      "outputs": [],
      "source": [
        "def make_model(src_vocab, tgt_vocab, N=6, d_model=512, d_ff=2048, h=8, dropout=0.1):\n",
        "    \"Construct a model object based on hyperparameters.\"\n",
        "    c = copy.deepcopy\n",
        "    attn = MultiHeadedAttention(h, d_model, dropout)\n",
        "    ff = PositionwiseFeedForward(d_model, d_ff, dropout)\n",
        "    position = PositionalEncoding(d_model, dropout)\n",
        "    model = EncoderDecoder(\n",
        "        Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N),\n",
        "        Decoder(DecoderLayer(d_model, c(attn), c(attn), c(ff), dropout), N),\n",
        "        nn.Sequential(Embeddings(d_model, src_vocab), c(position)),\n",
        "        nn.Sequential(Embeddings(d_model, tgt_vocab), c(position)),\n",
        "        Generator(d_model, tgt_vocab))\n",
        "\n",
        "    # This was important from their code. Initialize parameters with Glorot or fan_avg.\n",
        "    for p in model.parameters():\n",
        "        if p.dim() > 1:\n",
        "            nn.init.xavier_uniform(p)\n",
        "    return model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MuV1e8nEUgRB"
      },
      "source": [
        "# Training\n",
        "\n",
        "This section describes the training regime for our models.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Lz6n3REAUgRH"
      },
      "source": [
        "## Training Data and Batching\n",
        "\n",
        "We trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs.  Sentences were encoded using byte-pair encoding \\citep{DBLP:journals/corr/BritzGLL17}, which has a shared source-target vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT 2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece vocabulary [(cite)](wu2016google).\n",
        "\n",
        "\n",
        "Sentence pairs were batched together by approximate sequence length.  Each training batch contained a set of sentence pairs containing approximately 25000 source tokens and 25000 target tokens.     "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "52xwbbb4UgRK"
      },
      "source": [
        "## Hardware and Schedule                                                                                                                                                                                                   \n",
        "We trained our models on one machine with 8 NVIDIA P100 GPUs.  For our base models using the hyperparameters described throughout the paper, each training step took about 0.4 seconds.  We trained the base models for a total of 100,000 steps or 12 hours.  For our big models, step time was 1.0 seconds.  The big models were trained for 300,000 steps (3.5 days)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MPp__T_uUgRK"
      },
      "source": [
        "## Optimizer\n",
        "\n",
        "We used the Adam optimizer [(cite)](kingma2014adam) with $\\beta_1=0.9$, $\\beta_2=0.98$ and $\\epsilon=10^{-9}$.  We varied the learning rate over the course of training, according to the formula:                                                                                            \n",
        "$$                                                                                                                                                                                                                                                                                         \n",
        "lrate = d_{\\text{model}}^{-0.5} \\cdot                                                                                                                                                                                                                                                                                                \n",
        "  \\min({step\\_num}^{-0.5},                                                                                                                                                                                                                                                                                                  \n",
        "    {step\\_num} \\cdot {warmup\\_steps}^{-1.5})                                                                                                                                                                                                                                                                               \n",
        "$$                                                                                                                                                                                             \n",
        "This corresponds to increasing the learning rate linearly for the first $warmup\\_steps$ training steps, and decreasing it thereafter proportionally to the inverse square root of the step number.  We used $warmup\\_steps=4000$.           \n",
        "\n",
        "在前面的warmup_steps的训练步骤里，线性的增加学习率，然后随着步骤的平方根的倒数成正比进行衰减"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Q5yV0f2QUgRL"
      },
      "outputs": [],
      "source": [
        "# Note: This part is incredibly important.\n",
        "# Need to train with this setup of the model is very unstable.\n",
        "class NoamOpt:\n",
        "    \"Optim wrapper that implements rate.\"\n",
        "    def __init__(self, model_size, factor, warmup, optimizer):\n",
        "        self.optimizer = optimizer\n",
        "        self._step = 0\n",
        "        self.warmup = warmup\n",
        "        self.factor = factor\n",
        "        self.model_size = model_size\n",
        "        self._rate = 0\n",
        "\n",
        "    def step(self):\n",
        "        \"Update parameters and rate\"\n",
        "        self._step += 1\n",
        "        rate = self.rate()\n",
        "        for p in self.optimizer.param_groups:\n",
        "            p['lr'] = rate\n",
        "        self._rate = rate\n",
        "        self.optimizer.step()\n",
        "\n",
        "    def rate(self, step = None):\n",
        "        \"Implement `lrate` above\"\n",
        "        if step is None:\n",
        "            step = self._step\n",
        "        return self.factor * \\\n",
        "            (self.model_size ** (-0.5) *\n",
        "            min(step ** (-0.5), step * self.warmup**(-1.5)))\n",
        "\n",
        "def get_std_opt(model):\n",
        "    return NoamOpt(model.src_embed[0].d_model, 2, 4000,\n",
        "            torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FM5n1PJxUgRN"
      },
      "source": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 430
        },
        "id": "PC2wCVEFUgRO",
        "outputId": "71bd609c-1d96-4849-bac7-fb49cd0dc574"
      },
      "outputs": [],
      "source": [
        "# Three settings of the lrate hyperparameters.\n",
        "opts = [NoamOpt(512, 1, 4000, None),\n",
        "        NoamOpt(512, 1, 8000, None),\n",
        "        NoamOpt(256, 1, 4000, None)]\n",
        "plt.plot(np.arange(1, 20000), [[opt.rate(i) for opt in opts] for i in range(1, 20000)])\n",
        "plt.legend([\"512:4000\", \"512:8000\", \"256:4000\"])\n",
        "None"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8tkzxQYKUgRQ"
      },
      "source": [
        "## Regularization                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          \n",
        "                                                                                                                                                                                                                                                                                                                      \n",
        "### Label Smoothing\n",
        "\n",
        "During training, we employed label smoothing of value $\\epsilon_{ls}=0.1$ [(cite)](DBLP:journals/corr/SzegedyVISW15).  This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KVLADu1sCnOS"
      },
      "source": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IVWDJLXrUgRQ"
      },
      "outputs": [],
      "source": [
        "class LabelSmoothing(nn.Module):\n",
        "    \"Implement label smoothing.\"\n",
        "    def __init__(self, size, pad_token_id, smoothing=0.0):\n",
        "        super(LabelSmoothing, self).__init__()\n",
        "        #self.criterion = nn.KLDivLoss(size_average=False)\n",
        "        self.criterion = nn.KLDivLoss(reduction='sum')\n",
        "        self.pad_token_id = pad_token_id\n",
        "        self.confidence = 1.0 - smoothing\n",
        "        self.smoothing = smoothing\n",
        "        self.size = size #vocab_size\n",
        "        self.true_dist = None\n",
        "\n",
        "    def forward(self, x, target): #shape of x=[batch_size, vocab_size]，一个字符一个字符计算loss\n",
        "        assert x.size(1) == self.size\n",
        "        true_dist = x.data.clone()\n",
        "        true_dist.fill_(self.smoothing / (self.size - 2))#pad和目标标签不参与计算，亦即将真值位置之外的概率分布(smoothing)平摊到其他的token位置\n",
        "        true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)#将token真值的位置设为confidence，真值定义为soft label\n",
        "        true_dist[:, self.pad_token_id] = 0 #pad的token id为0，故true_dist(i)loginput(i)=0×loginput(i)=0，为0的位置在将不参与loss的计算，，也就是pad的token在vocab_size的divloss中不参与loss的计算\n",
        "        mask = torch.nonzero(target.data == self.pad_token_id)\n",
        "        if mask.dim() > 0:\n",
        "            true_dist.index_fill_(0, mask.squeeze(), 0.0)#从0维度进行填充，如果其对应的mask不为0，则这一行所有的分布为0，也就是token为pad的所有vocab_size都不参与loss的计算\n",
        "        self.true_dist = true_dist\n",
        "        return self.criterion(x, Variable(true_dist, requires_grad=False))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "LabelSmoothing使用示例 LabelSmoothing(5, 0, 0.5)，5为vocab_size，词汇表大小，0为pad的token id，0.5为smoothing因子\n",
        "predict为三个预测的输出的概率分布，crit即根据LabelSmoothing进行loss计算\n",
        "\n",
        "```\n",
        "torch.LongTensor([2, 1, 0]))-->\n",
        "\n",
        "tensor([[0.0000, 0.1667, 0.5000, 0.1667, 0.1667],\n",
        "        [0.0000, 0.5000, 0.1667, 0.1667, 0.1667],\n",
        "        [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]])\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 363
        },
        "id": "_gXwt5HVUgRT",
        "outputId": "d3f5d4c1-a0cf-4fce-d6e4-eaa1f1254f91"
      },
      "outputs": [],
      "source": [
        "#Example\n",
        "crit = LabelSmoothing(5, 0, 0.5)\n",
        "predict = torch.FloatTensor([[0, 0.2, 0.7, 0.1, 0],\n",
        "                             [0, 0.2, 0.7, 0.1, 0],\n",
        "                             [0, 0.2, 0.7, 0.1, 0]])\n",
        "v = crit(Variable(predict.log()),\n",
        "         Variable(torch.LongTensor([2, 1, 0])))\n",
        "\n",
        "# Show the target distributions expected by the system.\n",
        "plt.imshow(crit.true_dist)\n",
        "None"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "随着预测的准确度的增加，loss的下降可视化图示"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 465
        },
        "id": "sHBHTwmjUgRU",
        "outputId": "d480e533-51c1-4756-a00b-e21cec9e7e82"
      },
      "outputs": [],
      "source": [
        "# Label smoothing starts to penalize the model\n",
        "# if it gets very confident about a given choice\n",
        "# crit = LabelSmoothing(5, 0, 0.2)\n",
        "crit = nn.KLDivLoss(reduction='batchmean')\n",
        "def loss(x):\n",
        "    d = x + 3 * 1\n",
        "    predict = torch.FloatTensor([[1e-9, x / d, 1 / d, 1 / d, 1 / d],\n",
        "                                 ])\n",
        "    target = torch.FloatTensor([[0, 1, 0, 0, 0]])  # 使用one-hot向量作为目标分布\n",
        "    return crit(predict.log(), target).item()\n",
        "    #print(predict)\n",
        "    # return crit(Variable(predict.log()),\n",
        "    #              Variable(torch.LongTensor([1]))).item()\n",
        "print(loss(10.0))\n",
        "plt.plot(np.arange(1, 100), [loss(x) for x in range(1, 100)])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XoyfFgLoUgRW"
      },
      "source": [
        "### Memory Optimization"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "输出out的张量形状为out->[batch, max_seq_len， d_model],Variable(out[:, i].data为第i个token\n",
        "用时间换空间：通过一个循环，一次只处理序列中的一个时间步（一个 token），手动计算和累积梯度，从而避免一次性创建和存储那些巨大的中间张量。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yVKyONFsUgRW"
      },
      "outputs": [],
      "source": [
        "def loss_backprop(generator, criterion, out, targets, valid_token_counts):\n",
        "    \"\"\"\n",
        "    Memory optmization. Compute each timestep separately and sum grads.\n",
        "    \"\"\"\n",
        "    assert out.size(1) == targets.size(1)\n",
        "    total_loss = 0.0\n",
        "    total = 0.0\n",
        "    out_grad = []\n",
        "    #print(out.shape)torch.Size([2, 127, 512])\n",
        "    for i in range(out.size(1)): #out->[batch, max_seq_len， dmodel] for each token，这个循环遍历序列的每一个时间步（token），从 0到 T-1\n",
        "        # 将这个切片出的数据重新包装成一个新的叶子节点（leaf node）变量 out_column，并明确告诉 PyTorch 我们需要计算它相对于后续操作的梯度。这样做是为了构建一个临时的、局部的计算图。\n",
        "        # 1. Prepare a slice of the output tensor for this time step\n",
        "        # This slice is detached from the main graph to create a local computation graph.\n",
        "        out_column = Variable(out[:, i].data, requires_grad=True)\n",
        "        \n",
        "        # 2. Generate predictions for this time step\n",
        "        gen_out = generator(out_column) # Shape: [batch_size, vocab_size]\n",
        "        \n",
        "        # 3. Calculate the loss for this time step\n",
        "        # Note: criterion should be defined with reduction='none' to get per-element loss.\n",
        "        # e.g., criterion = nn.CrossEntropyLoss(reduction='none', ignore_index=padding_idx)\n",
        "        loss = criterion(gen_out, targets[:, i]) # Shape: [batch_size]\n",
        "        \n",
        "        # 4. Create a mask to filter out padding tokens for this time step\n",
        "        # A token is valid if its index 'i' is less than the total valid length.\n",
        "        mask = (i < valid_token_counts).float() # Shape: [batch_size]\n",
        "        \n",
        "        # 5. Apply the mask to the loss\n",
        "        masked_loss = loss * mask # Shape: [batch_size]\n",
        "        \n",
        "        # 6. Sum the loss for valid tokens and perform backpropagation\n",
        "        # We only backpropagate the loss from non-padded tokens.\n",
        "        # loss.sum() will correctly handle cases where some samples in the batch are masked out.\n",
        "        loss_sum = masked_loss.sum()\n",
        "        \n",
        "        # Accumulate total loss for reporting (normalized by the total number of valid tokens)\n",
        "        total_loss += loss_sum.item()\n",
        "\n",
        "        # Perform backpropagation on the local graph to get gradient w.r.t. out_column\n",
        "        # If loss_sum is 0 (e.g., all samples are padding at this step), no gradient is computed.\n",
        "        if loss_sum > 0:\n",
        "            loss_sum.backward()\n",
        "\n",
        "        # 7. Store the gradient\n",
        "        # If a sample was masked, its gradient will be zero, which is correct.\n",
        "        # We need to handle the case where out_column.grad is None if loss_sum was 0.\n",
        "        grad_data = out_column.grad.data.clone() if out_column.grad is not None else torch.zeros_like(out_column.data)\n",
        "        out_grad.append(grad_data)            \n",
        "    out_grad = torch.stack(out_grad, dim=1)\n",
        "    #这是连接主计算图并完成整个反向传播过程的魔法。\n",
        "    # 当在一个张量（非标量）上调用 .backward() 时，你需要提供一个 gradient 参数。\n",
        "    # 将我们手动计算并拼接好的梯度 out_grad (即 dL/d(out)) 作为起始梯度，从 out 节点开始，沿着主计算图继续向后传播，\n",
        "    # 从而计算出损失相对于模型中所有更早参数（如 Encoder、Decoder 的权重）的梯度。\n",
        "    out.backward(gradient=out_grad)\n",
        "    return total_loss"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sSF9AaKJUgRZ"
      },
      "outputs": [],
      "source": [
        "# 'input_ids': source['input_ids'].squeeze(),\n",
        "# 'src_atten_mask': source['attention_mask'].squeeze(),\n",
        "# 'tgt_atten_mask': target['attention_mask'].squeeze(),\n",
        "# 'labels': target['input_ids'].squeeze()  # 目标是英语的tokenized形式\n",
        "def train_epoch(train_iter, model, criterion, opt, transpose=False):\n",
        "    model.train()\n",
        "    for i, batch in enumerate(train_iter):\n",
        "        opt.optimizer.zero_grad()\n",
        "        # src, trg, src_mask, trg_mask = \\\n",
        "        #     batch.src, batch.trg, batch.src_mask, batch.trg_mask\n",
        "        #print(batch.keys())\n",
        "        #[2,1,128]\n",
        "        #print(batch['input_ids'].shape,batch['labels'].shape, batch['src_atten_mask'].shape, batch['tgt_atten_mask'].shape)\n",
        "        src, trg, src_mask, trg_mask = \\\n",
        "            batch['input_ids'], batch['labels'], batch['src_atten_mask'], batch['tgt_atten_mask']\n",
        "        #out = model.forward(src, trg[:, :-1], src_mask, trg_mask[:, :-1])\n",
        "        out = model.forward(src, trg, src_mask, trg_mask)\n",
        "        loss = loss_backprop(model.generator, criterion, out[:,:-1,:], trg[:, 1:], batch['valid_token_count'])\n",
        "\n",
        "        opt.step()\n",
        "\n",
        "        if i % 10 == 1:\n",
        "            print(i, loss, opt._rate)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "q4kFYs7nUgRb"
      },
      "outputs": [],
      "source": [
        "def valid_epoch(valid_iter, model, criterion, transpose=False):\n",
        "    model.test()\n",
        "    total = 0\n",
        "    for batch in valid_iter:\n",
        "        src, trg, src_mask, trg_mask = \\\n",
        "            batch.src, batch.trg, batch.src_mask, batch.trg_mask\n",
        "        out = model.forward(src, trg[:, :-1], src_mask, trg_mask[:, :-1, :-1])\n",
        "        loss = loss_backprop(model.generator, criterion, out, trg[:, 1:], batch.ntokens)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5S2BcIoOUgRg"
      },
      "source": [
        "# A Real World Example"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 591,
          "referenced_widgets": [
            "0655918e51444bbe8c0b42cc3e51918c",
            "d4afb00df36741eb9cbbcef62a5c8cae",
            "c28a9bf9015a46f9afb2bc4689da4668",
            "05932b9d17d64d4986406e77c73a580a",
            "1535450e41a3488284406c631e414dae",
            "1b623213778946c899dd8614a14bb076",
            "9e86dbf452814bdd8c39126cc55c77c8",
            "d670f02da52e463d840b5cbcab028789",
            "e503fe4383ae476a92815d99fb1cbf63",
            "a572b3aa25ab4e6696bac6e1a0ad53d0",
            "d0994f7f0a544edbb56ec82682f012a9",
            "4dae8dfadf7542528b2c684dfd3df51c",
            "6e583f9eec5344b392ee0e8ef6e1f9a7",
            "20dbb27bfd024511926de2d4d577c86b",
            "3446f50e672449f9bfa3a77aae0c9b9e",
            "49eef016a61c403d977db1029a754167",
            "5b4262c685504f1493fea9362464bc1d",
            "9d28f5217b7140cebf29e2b81f879a49",
            "f9efbed0ef03464abf99f90541fc0f6d",
            "2d25c2796cf648e99efcf5b5cba8033e",
            "aa5e9b8dfc2841fe9495dde65160a973",
            "82bcb45c60d246b895a6f311caaba538",
            "028ce27890c1447f97cbb6c0d27e11c7",
            "91e3a7d1547248fb92ad5d9416d907ad",
            "818a214f0f2d4d269c302753e8334fac",
            "94e4859654b1465682beb84df49536d7",
            "2822656db6ee42ff80ed918d5775d8a8",
            "42c337c7ed7e4210b4c311f0041d7b39",
            "52dd7e4c1263448d952af5a9071c208a",
            "f1e91350cf2b4029b3de1fe00d352775",
            "c90847011ec14db491acd4ad8c76e627",
            "fc4f217aef8a47d7b199ccc9bdcc8727",
            "aed17c92e74c48be8ae64ad97bb6ce42",
            "ffbb0349ef7d484d9b4e341a90557a6c",
            "87b30a0b94c646e3bbd1b98f593aeda5",
            "c754910114914c6d92153696c3b68d79",
            "0afdf8058a374e12ac3443b52b45621d",
            "fda0045025fd404aa2a4a920f4d10fe0",
            "6114cf00abe3494fa5ec14c35719fbf1",
            "351821e16f11413aa7591241d7e0a910",
            "f194ab2e492f4a27ad04d7b9fff1b0b7",
            "99e66ea12c3b4b45b81e6b48ca62b971",
            "69f53de64d764857976cdf6c6e423789",
            "3334c6e99bc049918186ac0d3747e2ee",
            "1d54fc6e1eaa44a1b42354c18fa5ebed",
            "275e3e2abbdc42adb8099cb7e0e4879e",
            "f218b106e5574213a967ae6f6992541b",
            "7df4e928dbf54277ada3c0ac8bc0fb15",
            "42037c0295154384b50f4d944d229187",
            "1dafa0f39af84f36b5422575c55ef3ae",
            "36602765b42b496b93b3bf1857d149be",
            "1595a9af8b844acfa32945321725f3a6",
            "fe3aa29f6d2e476cb4c377ad32e61a28",
            "760c0f1859e7437c89ec9da62ebbf2e0",
            "177143dae58e4ab7882c53151af6de2b",
            "641ca5a56cb946ada7f34ebe08b53ed4",
            "30f8f10d7c844cd285f3d70cfeac3168",
            "82874afa878a46c683d79e22c33e7bfc",
            "64059a24ff8b460fbe667ad6ad1cbb87",
            "c14ca547acca427db943eb000673a72f",
            "4c92a7e3e76249938aaa71e5409fd8bb",
            "b070a7eeaf7345dc8c21df3a896fafe8",
            "5cf66af097664590ab72b4e6b61410b0",
            "22ffce8007474ec08c26f9c6c87a176b",
            "591bf9d6b98446b8929cddcd2c9c7500",
            "3cfbe90b8a974464addbd175719fadec"
          ]
        },
        "id": "AMZWVjSnvC5C",
        "outputId": "e5037cf5-ff97-43e6-f889-f69969d10f28"
      },
      "outputs": [],
      "source": [
        "\n",
        "# from datasets import load_dataset\n",
        "\n",
        "# # 加载 IWSLT2017 数据集的德语到英语的翻译数据集\n",
        "# dataset = load_dataset('iwslt2017', 'iwslt2017-de-en',trust_remote_code=True)\n",
        "\n",
        "# # 查看数据集的结构\n",
        "# print(dataset)\n",
        "\n",
        "# # 数据集已经分为训练集、验证集和测试集\n",
        "# train_dataset = dataset['train']\n",
        "# validation_dataset = dataset['validation']\n",
        "# test_dataset = dataset['test']\n",
        "\n",
        "\n",
        "# # 示例：查看训练集中第一条数据\n",
        "# example = train_dataset[0]\n",
        "# print(f\"德语: {example['translation']['de']}\")\n",
        "# print(f\"英语: {example['translation']['en']}\")\n",
        "from datasets import load_dataset\n",
        "\n",
        "# 加载 IWSLT2017 数据集的德语到英语的翻译数据集\n",
        "dataset = load_dataset('iwslt2017', 'iwslt2017-zh-en',trust_remote_code=True)\n",
        "\n",
        "# 查看数据集的结构\n",
        "print(dataset)\n",
        "\n",
        "# 数据集已经分为训练集、验证集和测试集\n",
        "train_dataset = dataset['train']\n",
        "validation_dataset = dataset['validation']\n",
        "test_dataset = dataset['test']\n",
        "\n",
        "\n",
        "# 示例：查看训练集中第一条数据\n",
        "example = train_dataset[0]\n",
        "print(f\"中文: {example['translation']['zh']}\")\n",
        "print(f\"英语: {example['translation']['en']}\")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "非常谢谢，克里斯。的确非常荣幸 能有第二次站在这个台上的机会，我真是非常感激。\n",
        "\n",
        "torch.Size([1, 128]) tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
        "         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,\n",
        "         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
        "         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
        "         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
        "         0, 0, 0, 0, 0, 0, 0, 0]])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "zBaKFoTbvC5D",
        "outputId": "054d1428-6d5d-491b-8e92-98e9e4ef87a7"
      },
      "outputs": [],
      "source": [
        "from transformers import AutoTokenizer\n",
        "\n",
        "# 使用预训练的BERT tokenizer\n",
        "#tokenizer = AutoTokenizer.from_pretrained('bert-base-multilingual-cased')\n",
        "#BERT基于wordpiece\n",
        "#GPT基于BPE\n",
        "ch_tokenizer = AutoTokenizer.from_pretrained(\"bert-base-chinese\")\n",
        "en_tokenizer = AutoTokenizer.from_pretrained(\"bert-base-cased\")\n",
        "\n",
        "\n",
        "# 获取 [CLS] 和 [PAD] 的 token ID\n",
        "cls_token_id = en_tokenizer.convert_tokens_to_ids(en_tokenizer.cls_token)\n",
        "pad_token_id = en_tokenizer.convert_tokens_to_ids(en_tokenizer.pad_token)\n",
        "\n",
        "print(f\"[CLS] Token ID: {cls_token_id}\")\n",
        "print(f\"[PAD] Token ID: {pad_token_id}\")\n",
        "\n",
        "# 特殊标记\n",
        "bos_token = \"[CLS]\"  # 在BERT中，通常使用[CLS]作为开始标记\n",
        "sep_token = \"[SEP]\"  # 在BERT中，通常使用[SEP]作为结束标记\n",
        "\n",
        "# 定义最大序列长度\n",
        "max_seq_length = 128\n",
        "source = ch_tokenizer(\n",
        "    example['translation']['zh'],\n",
        "    padding='max_length',\n",
        "    truncation=True,\n",
        "    max_length=max_seq_length,\n",
        "    return_tensors='pt'\n",
        ")\n",
        "\n",
        "target = en_tokenizer(\n",
        "    f\"{bos_token} {example['translation']['en']} {sep_token}\",\n",
        "    padding='max_length',\n",
        "    truncation=True,\n",
        "    max_length=max_seq_length,\n",
        "    return_tensors='pt'\n",
        ")\n",
        "\n",
        "print(source['input_ids'].squeeze().shape, source['attention_mask'].squeeze().shape)\n",
        "print(source['attention_mask'].shape, source['attention_mask'])\n",
        "mask = source['attention_mask'].squeeze()\n",
        "#[128, 1],[1,128]\n",
        "att_mask = mask.unsqueeze(-1)@mask.unsqueeze(0)\n",
        "print(att_mask.shape, att_mask)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FAPitj1IvC5D"
      },
      "outputs": [],
      "source": [
        "def subsequent_mask_v2(size):\n",
        "    \"Mask out subsequent positions.\"\n",
        "    attn_shape = (size, size)\n",
        "    subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')\n",
        "    return torch.from_numpy(subsequent_mask) == 0"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "src_mask基于有效的token进行计算\n",
        "tgt_mask基于有效的token和causual masked的交操作进行计算"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "AEOoKB9vvC5E",
        "outputId": "b2fbd400-84eb-490e-e914-a02f8a8f1a73"
      },
      "outputs": [],
      "source": [
        "def make_std_mask(src_mask, tgt_mask, max_seq_len):\n",
        "    src_mask = src_mask.unsqueeze(-1)@src_mask.unsqueeze(0)\n",
        "    tgt_mask = tgt_mask.unsqueeze(-1)@tgt_mask.unsqueeze(0)\n",
        "    tgt_mask = tgt_mask & Variable(subsequent_mask_v2(max_seq_len).type_as(tgt_mask.data))\n",
        "    return src_mask, tgt_mask\n",
        "\n",
        "src_mask, tgt_mask = make_std_mask(source['attention_mask'].squeeze(), target['attention_mask'].squeeze(), max_seq_length)\n",
        "print(src_mask.shape, tgt_mask.shape, target['attention_mask'].sum(dim=1))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lXtYwdHqUgRj"
      },
      "outputs": [],
      "source": [
        "# 定义编码函数\n",
        "def encode_example(example):\n",
        "    source = ch_tokenizer(\n",
        "        example['translation']['zh'],\n",
        "        padding='max_length',\n",
        "        truncation=True,\n",
        "        max_length=max_seq_length,\n",
        "        return_tensors='pt'\n",
        "    )\n",
        "    target = en_tokenizer(\n",
        "        f\"{bos_token} {example['translation']['en']} {sep_token}\",\n",
        "        padding='max_length',\n",
        "        truncation=True,\n",
        "        max_length=max_seq_length,\n",
        "        return_tensors='pt'\n",
        "    )\n",
        "    src_mask, tgt_mask = make_std_mask(source['attention_mask'].squeeze(), target['attention_mask'].squeeze(), max_seq_length)\n",
        "    # 计算有效 token 的数目\n",
        "    valid_token_count = target['attention_mask'].sum(dim=1)\n",
        "    return {\n",
        "        'input_ids': source['input_ids'].squeeze(),\n",
        "        'src_atten_mask': src_mask,\n",
        "        'tgt_atten_mask': tgt_mask,\n",
        "        'valid_token_count':valid_token_count,\n",
        "        'labels': target['input_ids'].squeeze()  # 目标是英语的tokenized形式\n",
        "    }\n",
        "\n",
        "# 对数据集进行tokenization\n",
        "encoded_train_dataset = train_dataset.map(encode_example)\n",
        "encoded_validation_dataset = validation_dataset.map(encode_example)\n",
        "encoded_test_dataset = test_dataset.map(encode_example)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gVHU741gvC5E"
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "from torch.utils.data import Dataset, DataLoader\n",
        "\n",
        "class TranslationDataset(Dataset):\n",
        "    def __init__(self, encoded_dataset):\n",
        "        self.dataset = encoded_dataset\n",
        "\n",
        "    def __len__(self):\n",
        "        return len(self.dataset)\n",
        "\n",
        "    def __getitem__(self, idx):\n",
        "        return {\n",
        "            'input_ids': torch.tensor(self.dataset[idx]['input_ids'], dtype=torch.long),\n",
        "            'src_atten_mask': torch.tensor(self.dataset[idx]['src_atten_mask'], dtype=torch.long),\n",
        "            'tgt_atten_mask': torch.tensor(self.dataset[idx]['tgt_atten_mask'], dtype=torch.long),\n",
        "            'labels': torch.tensor(self.dataset[idx]['labels'], dtype=torch.long),\n",
        "            'valid_token_count': torch.tensor(self.dataset[idx]['valid_token_count'], dtype=torch.long),\n",
        "        }\n",
        "\n",
        "# 创建 PyTorch Dataset\n",
        "train_data = TranslationDataset(encoded_train_dataset)\n",
        "validation_data = TranslationDataset(encoded_validation_dataset)\n",
        "test_data = TranslationDataset(encoded_test_dataset)\n",
        "\n",
        "# 创建 DataLoader\n",
        "batch_size = 16\n",
        "train_dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=True)\n",
        "validation_dataloader = DataLoader(validation_data, batch_size=batch_size)\n",
        "test_dataloader = DataLoader(test_data, batch_size=batch_size)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "jLCQnla7vC5F",
        "outputId": "598dcb3e-64b0-4196-c66c-e0bc587702d9"
      },
      "outputs": [],
      "source": [
        "#引文有补齐时常用0，其代表的padding的含义\n",
        "print(ch_tokenizer.pad_token_id, en_tokenizer.pad_token_id, ch_tokenizer.vocab_size, en_tokenizer.vocab_size)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "wamR3SPdUgRo",
        "outputId": "30931390-b92b-4cf4-f3c7-567cc29cd8ad"
      },
      "outputs": [],
      "source": [
        "# Create the model an load it onto our GPU.\n",
        "#pad_idx = TGT.vocab.stoi[\"<blank>\"]\n",
        "# model = make_model(len(SRC.vocab), len(TGT.vocab), N=6)\n",
        "# model_opt = get_std_opt(model)\n",
        "# model.cuda()\n",
        "model = make_model(ch_tokenizer.vocab_size, en_tokenizer.vocab_size, N=6)\n",
        "model_opt = get_std_opt(model)\n",
        "#model.cuda()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "EeDTAXimvC5F",
        "outputId": "3f9fa0aa-bb41-4777-fb75-5cb6ec69f3c3"
      },
      "outputs": [],
      "source": [
        "\n",
        "criterion = LabelSmoothing(size=en_tokenizer.vocab_size, pad_token_id=en_tokenizer.pad_token_id, smoothing=0.1)\n",
        "#criterion.cuda()\n",
        "for epoch in range(15):\n",
        "    train_epoch(train_dataloader, model, criterion, model_opt)\n",
        "    valid_epoch(validation_dataloader, model, criterion)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1NO9lsw2UgRt"
      },
      "source": [
        "\n",
        "OTHER"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "B8BVm-hEUgRw"
      },
      "outputs": [],
      "source": [
        "BOS_WORD = '<s>'\n",
        "EOS_WORD = '</s>'\n",
        "BLANK_WORD = \"<blank>\"\n",
        "SRC = data.Field()\n",
        "TGT = data.Field(init_token = BOS_WORD, eos_token = EOS_WORD, pad_token=BLANK_WORD) # only target needs BOS/EOS\n",
        "\n",
        "MAX_LEN = 100\n",
        "train = datasets.TranslationDataset(path=\"/n/home00/srush/Data/baseline-1M_train.tok.shuf\",\n",
        "                                    exts=('.en', '.fr'),\n",
        "                                    fields=(SRC, TGT),\n",
        "                                    filter_pred=lambda x: len(vars(x)['src']) <= MAX_LEN and\n",
        "                                         len(vars(x)['trg']) <= MAX_LEN)\n",
        "SRC.build_vocab(train.src, max_size=50000)\n",
        "TGT.build_vocab(train.trg, max_size=50000)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "eFdZyOIzUgRx"
      },
      "outputs": [],
      "source": [
        "pad_idx = TGT.vocab.stoi[\"<blank>\"]\n",
        "print(pad_idx)\n",
        "model = make_model(len(SRC.vocab), len(TGT.vocab), pad_idx, N=6)\n",
        "model_opt = get_opt(model)\n",
        "model.cuda()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cinuTkbtUgRz"
      },
      "outputs": [],
      "source": [
        "criterion = LabelSmoothing(size=len(TGT.vocab), padding_idx=pad_idx, label_smoothing=0.1)\n",
        "criterion.cuda()\n",
        "for epoch in range(15):\n",
        "    train_epoch(train_iter, model, criterion, model_opt)\n",
        "    valid_epoch()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4LadFBIEUgR3"
      },
      "outputs": [],
      "source": [
        "print(pad_idx)\n",
        "print(len(SRC.vocab))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "kP_Au0bHUgR7"
      },
      "outputs": [],
      "source": [
        "torch.save(model, \"/n/rush_lab/trans_ipython.pt\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nqKKIhoOUgR-"
      },
      "outputs": [],
      "source": [
        "#weight = torch.ones(len(TGT.vocab))\n",
        "#weight[pad_idx] = 0\n",
        "#criterion = nn.NLLLoss(size_average=False, weight=weight.cuda())\n",
        "criterion = LabelSmoothing(size=len(TGT.vocab), padding_idx=pad_idx, label_smoothing=0.1)\n",
        "criterion.cuda()\n",
        "for epoch in range(15):\n",
        "    train_epoch(train_iter, model, criterion, model_opt)"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "torch-gpu",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.18"
    },
    "widgets": {
      "application/vnd.jupyter.widget-state+json": {
        "028ce27890c1447f97cbb6c0d27e11c7": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HBoxModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_91e3a7d1547248fb92ad5d9416d907ad",
              "IPY_MODEL_818a214f0f2d4d269c302753e8334fac",
              "IPY_MODEL_94e4859654b1465682beb84df49536d7"
            ],
            "layout": "IPY_MODEL_2822656db6ee42ff80ed918d5775d8a8"
          }
        },
        "05932b9d17d64d4986406e77c73a580a": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_a572b3aa25ab4e6696bac6e1a0ad53d0",
            "placeholder": "​",
            "style": "IPY_MODEL_d0994f7f0a544edbb56ec82682f012a9",
            "value": " 8.17k/8.17k [00:00&lt;00:00, 39.4kB/s]"
          }
        },
        "0655918e51444bbe8c0b42cc3e51918c": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HBoxModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_d4afb00df36741eb9cbbcef62a5c8cae",
              "IPY_MODEL_c28a9bf9015a46f9afb2bc4689da4668",
              "IPY_MODEL_05932b9d17d64d4986406e77c73a580a"
            ],
            "layout": "IPY_MODEL_1535450e41a3488284406c631e414dae"
          }
        },
        "0afdf8058a374e12ac3443b52b45621d": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_69f53de64d764857976cdf6c6e423789",
            "placeholder": "​",
            "style": "IPY_MODEL_3334c6e99bc049918186ac0d3747e2ee",
            "value": " 231266/231266 [00:05&lt;00:00, 42489.55 examples/s]"
          }
        },
        "1535450e41a3488284406c631e414dae": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "1595a9af8b844acfa32945321725f3a6": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "177143dae58e4ab7882c53151af6de2b": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "1b623213778946c899dd8614a14bb076": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "1d54fc6e1eaa44a1b42354c18fa5ebed": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HBoxModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_275e3e2abbdc42adb8099cb7e0e4879e",
              "IPY_MODEL_f218b106e5574213a967ae6f6992541b",
              "IPY_MODEL_7df4e928dbf54277ada3c0ac8bc0fb15"
            ],
            "layout": "IPY_MODEL_42037c0295154384b50f4d944d229187"
          }
        },
        "1dafa0f39af84f36b5422575c55ef3ae": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "20dbb27bfd024511926de2d4d577c86b": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "FloatProgressModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_f9efbed0ef03464abf99f90541fc0f6d",
            "max": 18506,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_2d25c2796cf648e99efcf5b5cba8033e",
            "value": 18506
          }
        },
        "22ffce8007474ec08c26f9c6c87a176b": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "ProgressStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "275e3e2abbdc42adb8099cb7e0e4879e": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_1dafa0f39af84f36b5422575c55ef3ae",
            "placeholder": "​",
            "style": "IPY_MODEL_36602765b42b496b93b3bf1857d149be",
            "value": "Generating test split: 100%"
          }
        },
        "2822656db6ee42ff80ed918d5775d8a8": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "2d25c2796cf648e99efcf5b5cba8033e": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "ProgressStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "30f8f10d7c844cd285f3d70cfeac3168": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_4c92a7e3e76249938aaa71e5409fd8bb",
            "placeholder": "​",
            "style": "IPY_MODEL_b070a7eeaf7345dc8c21df3a896fafe8",
            "value": "Generating validation split: 100%"
          }
        },
        "3334c6e99bc049918186ac0d3747e2ee": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "3446f50e672449f9bfa3a77aae0c9b9e": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_aa5e9b8dfc2841fe9495dde65160a973",
            "placeholder": "​",
            "style": "IPY_MODEL_82bcb45c60d246b895a6f311caaba538",
            "value": " 18.5k/18.5k [00:00&lt;00:00, 94.8kB/s]"
          }
        },
        "351821e16f11413aa7591241d7e0a910": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "36602765b42b496b93b3bf1857d149be": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "3cfbe90b8a974464addbd175719fadec": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "42037c0295154384b50f4d944d229187": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "42c337c7ed7e4210b4c311f0041d7b39": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "49eef016a61c403d977db1029a754167": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "4c92a7e3e76249938aaa71e5409fd8bb": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "4dae8dfadf7542528b2c684dfd3df51c": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HBoxModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_6e583f9eec5344b392ee0e8ef6e1f9a7",
              "IPY_MODEL_20dbb27bfd024511926de2d4d577c86b",
              "IPY_MODEL_3446f50e672449f9bfa3a77aae0c9b9e"
            ],
            "layout": "IPY_MODEL_49eef016a61c403d977db1029a754167"
          }
        },
        "52dd7e4c1263448d952af5a9071c208a": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "591bf9d6b98446b8929cddcd2c9c7500": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "5b4262c685504f1493fea9362464bc1d": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "5cf66af097664590ab72b4e6b61410b0": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "6114cf00abe3494fa5ec14c35719fbf1": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "64059a24ff8b460fbe667ad6ad1cbb87": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_591bf9d6b98446b8929cddcd2c9c7500",
            "placeholder": "​",
            "style": "IPY_MODEL_3cfbe90b8a974464addbd175719fadec",
            "value": " 879/879 [00:00&lt;00:00, 15875.00 examples/s]"
          }
        },
        "641ca5a56cb946ada7f34ebe08b53ed4": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HBoxModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_30f8f10d7c844cd285f3d70cfeac3168",
              "IPY_MODEL_82874afa878a46c683d79e22c33e7bfc",
              "IPY_MODEL_64059a24ff8b460fbe667ad6ad1cbb87"
            ],
            "layout": "IPY_MODEL_c14ca547acca427db943eb000673a72f"
          }
        },
        "69f53de64d764857976cdf6c6e423789": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "6e583f9eec5344b392ee0e8ef6e1f9a7": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_5b4262c685504f1493fea9362464bc1d",
            "placeholder": "​",
            "style": "IPY_MODEL_9d28f5217b7140cebf29e2b81f879a49",
            "value": "Downloading readme: 100%"
          }
        },
        "760c0f1859e7437c89ec9da62ebbf2e0": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "7df4e928dbf54277ada3c0ac8bc0fb15": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_760c0f1859e7437c89ec9da62ebbf2e0",
            "placeholder": "​",
            "style": "IPY_MODEL_177143dae58e4ab7882c53151af6de2b",
            "value": " 8549/8549 [00:00&lt;00:00, 37535.91 examples/s]"
          }
        },
        "818a214f0f2d4d269c302753e8334fac": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "FloatProgressModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_f1e91350cf2b4029b3de1fe00d352775",
            "max": 26849290,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_c90847011ec14db491acd4ad8c76e627",
            "value": 26849290
          }
        },
        "82874afa878a46c683d79e22c33e7bfc": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "FloatProgressModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_5cf66af097664590ab72b4e6b61410b0",
            "max": 879,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_22ffce8007474ec08c26f9c6c87a176b",
            "value": 879
          }
        },
        "82bcb45c60d246b895a6f311caaba538": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "87b30a0b94c646e3bbd1b98f593aeda5": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_6114cf00abe3494fa5ec14c35719fbf1",
            "placeholder": "​",
            "style": "IPY_MODEL_351821e16f11413aa7591241d7e0a910",
            "value": "Generating train split: 100%"
          }
        },
        "91e3a7d1547248fb92ad5d9416d907ad": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_42c337c7ed7e4210b4c311f0041d7b39",
            "placeholder": "​",
            "style": "IPY_MODEL_52dd7e4c1263448d952af5a9071c208a",
            "value": "Downloading data: 100%"
          }
        },
        "94e4859654b1465682beb84df49536d7": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_fc4f217aef8a47d7b199ccc9bdcc8727",
            "placeholder": "​",
            "style": "IPY_MODEL_aed17c92e74c48be8ae64ad97bb6ce42",
            "value": " 26.8M/26.8M [00:01&lt;00:00, 22.8MB/s]"
          }
        },
        "99e66ea12c3b4b45b81e6b48ca62b971": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "ProgressStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "9d28f5217b7140cebf29e2b81f879a49": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "9e86dbf452814bdd8c39126cc55c77c8": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "a572b3aa25ab4e6696bac6e1a0ad53d0": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "aa5e9b8dfc2841fe9495dde65160a973": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "aed17c92e74c48be8ae64ad97bb6ce42": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "b070a7eeaf7345dc8c21df3a896fafe8": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "c14ca547acca427db943eb000673a72f": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "c28a9bf9015a46f9afb2bc4689da4668": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "FloatProgressModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_d670f02da52e463d840b5cbcab028789",
            "max": 8170,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_e503fe4383ae476a92815d99fb1cbf63",
            "value": 8170
          }
        },
        "c754910114914c6d92153696c3b68d79": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "FloatProgressModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_f194ab2e492f4a27ad04d7b9fff1b0b7",
            "max": 231266,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_99e66ea12c3b4b45b81e6b48ca62b971",
            "value": 231266
          }
        },
        "c90847011ec14db491acd4ad8c76e627": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "ProgressStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "d0994f7f0a544edbb56ec82682f012a9": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "DescriptionStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "d4afb00df36741eb9cbbcef62a5c8cae": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HTMLModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_1b623213778946c899dd8614a14bb076",
            "placeholder": "​",
            "style": "IPY_MODEL_9e86dbf452814bdd8c39126cc55c77c8",
            "value": "Downloading builder script: 100%"
          }
        },
        "d670f02da52e463d840b5cbcab028789": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "e503fe4383ae476a92815d99fb1cbf63": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "ProgressStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "f194ab2e492f4a27ad04d7b9fff1b0b7": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "f1e91350cf2b4029b3de1fe00d352775": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "f218b106e5574213a967ae6f6992541b": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "FloatProgressModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_1595a9af8b844acfa32945321725f3a6",
            "max": 8549,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_fe3aa29f6d2e476cb4c377ad32e61a28",
            "value": 8549
          }
        },
        "f9efbed0ef03464abf99f90541fc0f6d": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "fc4f217aef8a47d7b199ccc9bdcc8727": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "fda0045025fd404aa2a4a920f4d10fe0": {
          "model_module": "@jupyter-widgets/base",
          "model_module_version": "1.2.0",
          "model_name": "LayoutModel",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "fe3aa29f6d2e476cb4c377ad32e61a28": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "ProgressStyleModel",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "ffbb0349ef7d484d9b4e341a90557a6c": {
          "model_module": "@jupyter-widgets/controls",
          "model_module_version": "1.5.0",
          "model_name": "HBoxModel",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_87b30a0b94c646e3bbd1b98f593aeda5",
              "IPY_MODEL_c754910114914c6d92153696c3b68d79",
              "IPY_MODEL_0afdf8058a374e12ac3443b52b45621d"
            ],
            "layout": "IPY_MODEL_fda0045025fd404aa2a4a920f4d10fe0"
          }
        }
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
